package com.csdj.utils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class RedisUtil {
    //1.私有的构造方法
    private RedisUtil(){}

    static JedisPool pool=null;

    /**
     * 被访问内部静态类的成员时才加载
     */
    static class Inner {

        static JedisPool pool = initPool();
    }

     static JedisPool initPool(){
         final InputStream is = RedisUtil.class.getClassLoader().getResourceAsStream("redis.properties");
         Properties properties = new Properties();
         try {
             properties.load(is);
         } catch (IOException e) {
             e.printStackTrace();
         }
         String host = properties.getProperty("host","localhost");
         final String portStr = properties.getProperty("port", "6379");
         final String password = properties.getProperty("password", "123456");


         GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxTotal(20);
        config.setMinIdle(2);


        JedisPool pool = new JedisPool(config,host, Integer.parseInt(portStr),3000,password);
        Jedis resource = pool.getResource();
        String value = resource.get("jedis");
        System.out.println(value);
        resource.close();//回收连接
        //pool.close();//关闭池子
         return pool;
    }

    public static Jedis getResource(){
        return Inner.pool.getResource();
    }

    public static String getString(String key){
        Jedis resource =null;
        try{
            resource = getResource();
            if(resource != null ){
                return resource.get(key);
            }
            return null;
        }finally {
            if(resource != null){
                System.out.println("关闭redis");
                resource.close();
            }

        }

    }

    /*//内部静态类
    static class JedisPool{


    }*/

    public static Jedis jedis(){
        Jedis client = new Jedis("localhost",6379);
        client.auth("123456");
        client.close();//关闭
        return client;
    }

}
